package nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by yu756 on 2020/1/5 21:10
 */
public class NioServer {
    public static void main(String[] args) throws Exception {
        //  1 创建ServerSocketChannel --> ServerSocket
        ServerSocketChannel serverSockeretChannel = ServerSocketChannel.open();
        // 2 得到selector对象
        Selector selector = Selector.open();
        // 绑定端口  在服务端监听
        serverSockeretChannel.socket().bind(new InetSocketAddress(6666));
        // 设置非阻塞模式
        serverSockeretChannel.configureBlocking(false);
        // 把 serverSockeretChannel 注册到 selector 关心事件OP_ACCEPT
        serverSockeretChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            // 无事情发生
            if (selector.select(1000) == 0) {
                System.out.println("服务器等待1S，无连接");
                continue;
            }
            //如果返回大于0 就获取相关的 selectionKey集合
            // 关注事情的集合  selectionKeys 反向获取通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                // 获取selectionKey
                SelectionKey key = keyIterator.next();
                //根据key 对应通道发生的事情处理
                if (key.isAcceptable()) {  // 如果是OP_ ACCEPT 有新的客户端链接
                    // 给该客户端生成socketChannel
                    SocketChannel socketChannel = serverSockeretChannel.accept();
                    System.out.println("客户端连接成功" + socketChannel.hashCode());
                    // 将socketChannel 设置为非阻塞
                    socketChannel.configureBlocking(false);
                    // 将socketChannel 注册到selector 关注事件为 OP_READ同时   socketChannel关联一个buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                }
                if (key.isReadable()) {
                    //通过key 反向获取channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    // 获取到该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("form client ----" + new String(buffer.array()));
                }
                // 手动从集合中移除当前selectionKey，防止重复操作
                keyIterator.remove();

            }


        }

    }
}
